let token = '';

// API基础URL
const API_BASE_URL = 'http://localhost:3001/api';

// DOM元素
const loginForm = document.getElementById('loginFormElement');
const regionManagement = document.getElementById('regionManagement');
const addRegionForm = document.getElementById('addRegionForm');
const regionList = document.getElementById('regionList');

// 登录处理
loginForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    try {
        console.log('正在登录...');
        const response = await fetch(`${API_BASE_URL}/users/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });

        const data = await response.json();
        console.log('登录响应:', data);

        if (response.ok) {
            localStorage.setItem('token', data.token);
            showAlert('登录成功', 'success');
            // 隐藏登录表单，显示区域管理
            document.getElementById('loginForm').classList.add('d-none');
            document.getElementById('regionManagement').classList.remove('d-none');
            loadRegions();
        } else {
            showAlert(data.message || '登录失败', 'danger');
        }
    } catch (error) {
        console.error('登录错误:', error);
        showAlert('登录请求失败', 'danger');
    }
});

// 添加区域处理
addRegionForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const name = document.getElementById('regionName').value;
    const code = document.getElementById('regionCode').value;
    const level = parseInt(document.getElementById('regionLevel').value);

    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showAlert('请先登录', 'warning');
            return;
        }

        console.log('正在添加区域...');
        const response = await fetch(`${API_BASE_URL}/regions`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({ name, code, level })
        });

        const data = await response.json();
        console.log('添加区域响应:', data);

        if (response.ok) {
            addRegionForm.reset();
            loadRegions();
            showAlert('区域添加成功', 'success');
        } else {
            showAlert(data.message || '添加失败', 'danger');
        }
    } catch (error) {
        console.error('添加区域错误:', error);
        showAlert('添加区域请求失败', 'danger');
    }
});

// 加载区域列表
async function loadRegions() {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showAlert('请先登录', 'warning');
            return;
        }

        console.log('正在加载区域列表...');
        console.log('Token:', token);
        console.log('API URL:', `${API_BASE_URL}/regions`);

        const response = await fetch(`${API_BASE_URL}/regions`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });

        console.log('响应状态:', response.status);
        const data = await response.json();
        console.log('区域列表数据:', data);

        if (response.ok) {
            // 从data.data.items中获取区域列表
            const regions = Array.isArray(data.data.items) ? data.data.items : [];
            console.log('处理后的区域列表:', regions);
            renderRegions(regions);
        } else {
            showAlert(data.message || '加载区域列表失败', 'danger');
        }
    } catch (error) {
        console.error('加载区域列表错误:', error);
        showAlert('加载区域列表失败', 'danger');
    }
}

// 渲染区域列表
function renderRegions(regions) {
    const regionList = document.getElementById('regionList');
    if (!Array.isArray(regions) || regions.length === 0) {
        regionList.innerHTML = '<tr><td colspan="5" class="text-center">暂无数据</td></tr>';
        return;
    }

    regionList.innerHTML = regions.map(region => `
        <tr>
            <td>${region.id}</td>
            <td>${region.name}</td>
            <td>${region.code}</td>
            <td>${region.level}</td>
            <td>
                <button class="btn btn-sm btn-primary btn-edit" data-id="${region.id}">编辑</button>
                <button class="btn btn-sm btn-danger btn-delete" data-id="${region.id}">删除</button>
            </td>
        </tr>
    `).join('');
}

// 编辑区域
async function editRegion(id) {
    try {
        console.log('正在获取区域信息...', id);
        const response = await fetch(`${API_BASE_URL}/regions/${id}`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        const data = await response.json();
        console.log('区域信息响应:', data);

        if (response.ok) {
            const region = data.data;
            // 填充模态框表单
            document.getElementById('editRegionId').value = region.id;
            document.getElementById('editRegionName').value = region.name;
            document.getElementById('editRegionCode').value = region.code;
            document.getElementById('editRegionLevel').value = region.level;
            
            // 显示模态框
            const editModal = new bootstrap.Modal(document.getElementById('editRegionModal'));
            editModal.show();
        } else {
            showAlert(data.message || '获取区域信息失败', 'danger');
        }
    } catch (error) {
        console.error('获取区域错误:', error);
        showAlert('获取区域信息失败，请重试', 'danger');
    }
}

// 保存编辑的区域
async function saveEditRegion() {
    const id = document.getElementById('editRegionId').value;
    const name = document.getElementById('editRegionName').value;
    const code = document.getElementById('editRegionCode').value;
    const level = parseInt(document.getElementById('editRegionLevel').value);

    try {
        console.log('正在更新区域...', id);
        const response = await fetch(`${API_BASE_URL}/regions/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({ name, code, level })
        });

        const data = await response.json();
        console.log('更新区域响应:', data);

        if (response.ok) {
            // 关闭模态框
            const editModal = bootstrap.Modal.getInstance(document.getElementById('editRegionModal'));
            editModal.hide();
            
            // 刷新区域列表
            loadRegions();
            showAlert('更新成功', 'success');
        } else {
            showAlert(data.message || '更新失败', 'danger');
        }
    } catch (error) {
        console.error('更新区域错误:', error);
        showAlert('更新失败，请重试', 'danger');
    }
}

// 删除区域
async function deleteRegion(id) {
    if (!confirm('确定要删除这个区域吗？')) {
        return;
    }

    try {
        console.log('正在删除区域...', id);
        const response = await fetch(`${API_BASE_URL}/regions/${id}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        const data = await response.json();
        console.log('删除区域响应:', data);

        if (response.ok) {
            loadRegions();
            showAlert('删除成功', 'success');
        } else {
            showAlert(data.message || '删除失败', 'danger');
        }
    } catch (error) {
        console.error('删除区域错误:', error);
        showAlert('删除失败，请重试', 'danger');
    }
}

// 保存原始表单提交处理函数
addRegionForm.originalSubmit = addRegionForm.onsubmit;

// 显示提示信息
function showAlert(message, type = 'info') {
    const alertDiv = document.getElementById('alert');
    alertDiv.textContent = message;
    alertDiv.className = `alert alert-${type}`;
    alertDiv.classList.remove('d-none');
    
    // 3秒后自动隐藏
    setTimeout(() => {
        alertDiv.classList.add('d-none');
    }, 3000);
}

// 页面加载时检查登录状态
document.addEventListener('DOMContentLoaded', () => {
    // 清除本地存储的token
    localStorage.removeItem('token');
    
    // 确保显示登录界面，隐藏管理界面
    document.getElementById('loginForm').classList.remove('d-none');
    document.getElementById('regionManagement').classList.add('d-none');

    // 绑定登录表单提交事件
    document.getElementById('loginFormElement').addEventListener('submit', async (e) => {
        e.preventDefault();
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        try {
            console.log('正在登录...');
            const response = await fetch(`${API_BASE_URL}/users/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            });

            const data = await response.json();
            console.log('登录响应:', data);

            if (response.ok) {
                localStorage.setItem('token', data.token);
                document.getElementById('loginForm').classList.add('d-none');
                document.getElementById('regionManagement').classList.remove('d-none');
                loadRegions();
                showAlert('登录成功', 'success');
            } else {
                showAlert(data.message || '登录失败', 'danger');
            }
        } catch (error) {
            console.error('登录错误:', error);
            showAlert('登录请求失败', 'danger');
        }
    });

    // 绑定退出登录按钮事件
    document.getElementById('logoutBtn').addEventListener('click', logout);

    // 绑定添加区域表单提交事件
    document.getElementById('addRegionForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const name = document.getElementById('regionName').value;
        const code = document.getElementById('regionCode').value;
        const level = parseInt(document.getElementById('regionLevel').value);

        try {
            const token = localStorage.getItem('token');
            if (!token) {
                showAlert('请先登录', 'warning');
                return;
            }

            console.log('正在添加区域...');
            const response = await fetch(`${API_BASE_URL}/regions`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ name, code, level })
            });

            const data = await response.json();
            console.log('添加区域响应:', data);

            if (response.ok) {
                document.getElementById('addRegionForm').reset();
                loadRegions();
                showAlert('区域添加成功', 'success');
            } else {
                showAlert(data.message || '添加失败', 'danger');
            }
        } catch (error) {
            console.error('添加区域错误:', error);
            showAlert('添加区域请求失败', 'danger');
        }
    });

    // 绑定保存编辑按钮事件
    document.getElementById('saveEditRegion').addEventListener('click', saveEditRegion);

    // 使用事件委托处理编辑和删除按钮的点击事件
    document.getElementById('regionList').addEventListener('click', async (e) => {
        const target = e.target;
        if (target.classList.contains('btn-edit')) {
            const id = target.dataset.id;
            await editRegion(id);
        } else if (target.classList.contains('btn-delete')) {
            const id = target.dataset.id;
            await deleteRegion(id);
        }
    });
});

// 退出登录
function logout() {
    localStorage.removeItem('token');
    document.getElementById('loginForm').classList.remove('d-none');
    document.getElementById('regionManagement').classList.add('d-none');
    showAlert('已退出登录', 'info');
}